package com.cloud.school.app.service.impl;

import com.cloud.school.app.entity.TbImage;
import com.cloud.school.app.mapstruct.IImageConvertMapper;
import com.cloud.school.app.model.ImageModel;
import com.cloud.school.app.repository.TbImageMapper;
import com.cloud.school.app.service.ImageService;
import com.cloud.school.app.util.FileUtils;
import com.cloud.school.app.util.IdWorker;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName ImageServiceImpl
 * @Description TODO
 * @Author 36297
 * @Date 2018/12/14 0:54
 * @Version 1.0
 */
@Service
public class ImageServiceImpl implements ImageService {

    @Autowired
    private IdWorker imageIdWorker;
    @Autowired
    private TbImageMapper tbImageMapper;
    @Autowired
    private IImageConvertMapper imageConvertMapper;

    @Override
    @Transactional
    public ImageModel save(MultipartFile file, Long userId) {
        String fileUrl = FileUtils.uploadFile(file);
        if (!StringUtils.isEmpty(fileUrl)) {
            TbImage image = new TbImage();
            image.setCreateTime(System.currentTimeMillis());
            image.setCreateUid(userId);
            image.setPath(fileUrl);
            image.setName(fileUrl.substring(fileUrl.lastIndexOf("/") + 1));
            image.setId(imageIdWorker.nextId());
            tbImageMapper.insertSelective(image);
            return imageConvertMapper.entityToModel(image);
        }
        return null;
    }

    @Override
    public ImageModel seleteById(Long imageId) {
        return imageConvertMapper.entityToModel(tbImageMapper.selectByPrimaryKey(imageId));
    }

    @Override
    public List<ImageModel> seleteByIds(List<Long> imageIds) {
        if (CollectionUtils.isEmpty(imageIds)) {
            return Lists.newArrayList();
        }
        String imageIdArrayString = String.join(",", imageIds.stream().distinct().map(id -> id.toString()).collect(Collectors.toList()));
        return imageConvertMapper.entityToModel(tbImageMapper.selectByIds(imageIdArrayString));
    }

    @Override
    @Transactional
    public boolean delete(Long imageId) {
        TbImage image = tbImageMapper.selectByPrimaryKey(imageId);
        int i = tbImageMapper.deleteByPrimaryKey(imageId);
        if (image != null && !StringUtils.isEmpty(image.getPath())) {
            FileUtils.deleteFile(image.getPath());
        }
        return i > 0;
    }
}
